package at.fhj.antesk.steamvaluecalc.view;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.fhj.antesk.steamvaluecalc.resources.Configs;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Map;
import java.awt.Toolkit;


public class LoadingWindow extends JFrame {

	private static final long serialVersionUID = -7699551680201617031L;
	private JPanel contentPane;
	private JProgressBar progressBar;
	private Thread target;
	private static Logger logger = LoggerFactory.getLogger(LoadingWindow.class);
	private Map<String, String> configsMap = Configs.getInstance().getConfigsMap();

	public LoadingWindow() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(LoadingWindow.class.getResource("/resources/spicon.gif")));
		setupFrameProperties();
		setupContentPane();
		setupProgressBar();
		setupCancelButton();
	}

	private void setupCancelButton() {
		JButton btnCancel = new JButton(configsMap.get("loadingwindow.button.cancel"));
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					target.stop();
					LoadingWindow.this.setVisible(false);
					logger.debug("Price Retrieving cancelled with Thread.stop()");
				} catch (Exception e1) {
					logger.error("Error while stopping priceRetrieverThread.", e1);
				}
			}
		});
		btnCancel.setBounds(236, 49, 89, 23);
		contentPane.add(btnCancel);
	}

	private void setupProgressBar() {
		progressBar = new JProgressBar();
		progressBar.setBorder(null);
		progressBar.setBackground(Color.DARK_GRAY);
		progressBar.setForeground(Color.LIGHT_GRAY);
		progressBar.setStringPainted(true);
		progressBar.setBounds(0, 0, 335, 43);
		contentPane.add(progressBar);
	}

	private void setupContentPane() {
		contentPane = new JPanel();
		contentPane.setBackground(Color.DARK_GRAY);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
	}

	private void setupFrameProperties() {
		setAlwaysOnTop(true);
		setBackground(Color.DARK_GRAY);
		setTitle(configsMap.get("loadingwindow.title"));
		setResizable(false);
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setBounds(100, 100, 341, 106);
		setLocationRelativeTo(null);
	}

	public JProgressBar getProgressBar() {
		return progressBar;
	}

	public void setTarget(Thread target) {
		this.target = target;
	}
}
